<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/9
 * Time: 11:06
 */

namespace Admin\Controller;

use Common\Controller\AdminController;
use Think\Page;

class NewsController extends AdminController
{
    /*
     * 资讯列表
     * */
    public function index()
    {
        $keyword = I('get.keyword','','htmlspecialchars');
        $search = I('get.search','','htmlspecialchars');
        $News = M('News');

        if (!empty($keyword)) {
            $where['news_tittle|news_content|news_author']  = array('like', "%$keyword%");
        }

        if (!empty($search)) {
            $where['news_type'] = array('eq',$search);
        }

        $dataCount = $News->where($where)->count();

        $page = new Page($dataCount, 10);
        $show = $page->show();

        $data = $News->where($where)->limit($page->firstRow, $page->listRows)->select();

        $this->assign('data',$data);
        $this->assign('show',$show);

        layout(true);
        $this->display('index');
    }

    /*
     * 发布资讯
     * */
    public function addNews()
    {
        $News = D('News'); //D参数：模型名 默认当前模块下的Model
        if (IS_POST) {
            $array=I('post.');
            $array['creat_time']=date('Y-m-d H:i:s');
            if ($News->create() && $News->add($array)) {
                //添加成功
                $this->success('添加成功', '/News/index');
                return;
            } else {
                // 自动验证没有通过 输出错误提示信息
                $errData = $News->getError();
                $this->assign('errData',$errData);
            }
        }
        layout(true);
        $this->display('add_news');
    }

    /*
     * 修改资讯
     * */
    public function modNews($news_id)
    {
        $news_id = intval($news_id);
        $News =D('News');
        $data = $News->where(array(
            'news_id' => $news_id
        ))->find();

        if (!$data) {
            $this->redirect('/News/index');
        }

        if (IS_POST) {
            if ($News->create() && $News->save()) {
                $this->success('修改成功', '/News/index');
                return;
            } else {
                // 自动验证没有通过 输出错误提示信息
                $errData = $News->getError();
                $this->assign('errData',$errData);
            }
        }
        $this->assign('data',$data);

        layout(true);
        $this->display('mod_news');
    }

    /*
     * 删除资讯
     * */
    public function delNews($news_id)
    {
        $news_id = intval($news_id);
        $News = M('News');
        $findData = $News->where(array(
            'news_id' => $news_id
        ))->find();

        if ($findData) {
            $News->delete($news_id);
            $this->success('删除成功', '/News/index');
        } else {
            $this->error('删除失败', '/News/index');
        }
    }
}